package com.library.librarybackend.controller;

import com.library.librarybackend.domain.ResponseWithPage;
import com.library.librarybackend.domain.Result;
import com.library.librarybackend.domain.dto.BookQueryDTO;
import com.library.librarybackend.domain.dto.BookUploadFormDTO;
import com.library.librarybackend.domain.vo.AttachmentVO;
import com.library.librarybackend.domain.vo.BookVO;
import com.library.librarybackend.service.AttachmentService;
import com.library.librarybackend.service.BookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;

/**
 * @author 平
 * @description 书籍控制类
 * @since 2025-09-21 13:40
 */
@Tag(name = "书籍控制类")
@RestController
@RequiredArgsConstructor
@RequestMapping("/book")
public class BookController {

    private final BookService bookService;
    private final AttachmentService attachmentService;

    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    @Operation(summary = "上传书籍")
    public Result<BookVO> upload(@ModelAttribute @Validated BookUploadFormDTO bookUploadFormDTO) {
        return Result.success(bookService.upload(bookUploadFormDTO));
    }

    @PostMapping(value = "/query")
    @Operation(summary = "查询书籍")
    public Result<ResponseWithPage<BookVO>> queryPage(@RequestBody @Validated BookQueryDTO bookQueryDTO) {
        return Result.success(bookService.queryPage(bookQueryDTO));
    }

    @GetMapping(value = "/download")
    public ResponseEntity<Resource> download(@RequestParam Long id, @RequestParam String objName) {
        // 查询附件
        AttachmentVO attachmentVO = attachmentService.queryByObjName(objName);
        // 下载附件
        InputStream inputStream = bookService.download(id, objName);
        // 创建InputStreamResource
        InputStreamResource resource = new InputStreamResource(inputStream);

        HttpHeaders headers = AttachmentController.getHeaders(objName);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(attachmentVO.getSize())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable Long id) {
        return bookService.removeById(id) ? Result.success() : Result.error();
    }

}
